package com.ayoka.ui.assignment;

import android.Manifest;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.ayoka.R;
import com.ayoka.base.BaseFragment;
import com.ayoka.bean.CourseAssignmentBean;
import com.ayoka.bean.CourseAssignmentBean.VideoQuestionBean;
import com.ayoka.databinding.FragmentCourseAssignmentVideoBinding;
import com.ayoka.mvp.CourseAssignmentVideoMVP.CourseAssignmentVideoModel.SubmitCourseAssignmentBean;
import com.ayoka.mvp.CourseAssignmentVideoMVP.CourseAssignmentVideoPresenter;
import com.ayoka.mvp.CourseAssignmentVideoMVP.ICourseAssignmentVideoView;
import com.ayoka.mvp.CourseAssignmentVideoMVP.CourseAssignmentVideoModel.SubmitCourseAssignmentVideoAnswerBean;
import com.ayoka.utils.AudioManagerEvent;
import com.ayoka.utils.CourseEvent;
import com.ayoka.utils.MediaManager;
import com.ayoka.widget.RecordAudioButton;
import com.jcp.baselibrary.permission.MPermission;
import com.jcp.baselibrary.utils.DateUtil;
import com.jcp.baselibrary.utils.UIUtils;
import com.jincp.image.load.ImageLoaderProxy;
import com.jzvd.JZMediaIjkplayer;
import com.jzvd.SimpleJZMediaPlayerListener;

import java.io.File;
import java.util.Observable;
import java.util.Timer;
import java.util.TimerTask;

import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;


public class CourseAssignmentVideoFragment extends BaseFragment<FragmentCourseAssignmentVideoBinding, CourseAssignmentVideoPresenter> implements ICourseAssignmentVideoView, RecordAudioButton.IRecordAudioListener {

    public static final long DEFAULT_MAX_RECORD_TIME = 120000;
    public static final long DEFAULT_MIN_RECORD_TIME = 2000;
    protected static final int DEFAULT_MIN_TIME_UPDATE_TIME = 1000;

    public static CourseAssignmentVideoFragment newInstance(CourseAssignmentBean courseAssignmentBean) {
        CourseAssignmentVideoFragment assignmentFragment = new CourseAssignmentVideoFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("CourseAssignmentBean", courseAssignmentBean);
        assignmentFragment.setArguments(bundle);
        return assignmentFragment;
    }

    protected CourseAssignmentBean courseAssignmentBean;

    private int currentIndex, totalQuestionCount;
    private VideoQuestionBean videoQuestionBean;

    // 录音
    private File audioFile;
    private String audioFileName;
    private long maxRecordTime = DEFAULT_MAX_RECORD_TIME;
    private long minRecordTime = DEFAULT_MIN_RECORD_TIME;
    private long recordTotalTime;
    private long durationTime;
    private Timer timer;
    private TimerTask timerTask;

    @Override
    protected void configBundleArguments() {
        courseAssignmentBean = (CourseAssignmentBean) getArguments().getSerializable("CourseAssignmentBean");
        totalQuestionCount = courseAssignmentBean.VideoQuestions.size();
    }

    @Override
    public int getContentLayout() {
        return R.layout.fragment_course_assignment_video;
    }

    @Override
    protected void initViews(View view) {
        mDataBinding.ivDeleteVoice.setColorFilter(Color.parseColor("#e3e3e3"));
        mDataBinding.btnSubmit.setOnClickListener(this);

        // 设置录音按钮的监听事件
        mDataBinding.recordAudioButton.setRecordAudioListener(this);
        mDataBinding.ivSoundAnimator.setOnClickListener(this);
        mDataBinding.ivDeleteVoice.setOnClickListener(this);
    }

    @Override
    public void initData() {
        if (!MPermission.hasPermissions(getActivity(), permissions)){
            MPermission.with(this).permissions(permissions).request();
        }
        // 设置监听
        MediaManager.getInstance().addObserver(this);
        AudioManagerEvent.getInstance().addObserver(this);
        AudioManagerEvent.getInstance().requestAudioFocus();

        configQuestion();
    }

    @Override
    protected CourseAssignmentVideoPresenter getPresenter() {
        return new CourseAssignmentVideoPresenter();
    }

    private void configQuestion() {
        videoQuestionBean = courseAssignmentBean.VideoQuestions.get(currentIndex);
        mDataBinding.tvQuestion.setText(videoQuestionBean.Question);

        // 设置视频地址
        JZVideoPlayer.releaseAllVideos();
        MediaManager.getInstance().release();
        mDataBinding.videoPlayer.setUp(videoQuestionBean.VideoUrl, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, courseAssignmentBean.Title);
        // 增加封面
        ImageLoaderProxy.getInstance().displayImage(videoQuestionBean.ImgUrl, mDataBinding.videoPlayer.thumbImageView);
        JZVideoPlayer.setMediaInterface(new JZMediaIjkplayer());
        mDataBinding.videoPlayer.setJZMediaPlayerListener(new SimpleJZMediaPlayerListener(){
            @Override
            public void onStateAutoComplete() {
                Log.d(TAG, "onAutoComplete");
            }
        });
        // 自动播放
        mDataBinding.videoPlayer.startButton.performClick();

        if (videoQuestionBean.QuestionType == 0) {
            mDataBinding.llVoiceShowLayout.setVisibility(View.VISIBLE);
            mDataBinding.llVoiceInputLayout.setVisibility(View.GONE);
            mDataBinding.llVoiceShowContainer.setVisibility(View.GONE);
        } else {
            mDataBinding.llVoiceShowLayout.setVisibility(View.GONE);
            mDataBinding.llVoiceInputLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDataBinding.btnSubmit) {
           JZVideoPlayer.goOnPlayOnPause();
            if (videoQuestionBean.QuestionType == 0) {
                if (currentIndex == totalQuestionCount - 1) {
                    mPresenter.postCourseAssignmentVideoRecord(courseAssignmentBean);
                } else {
                    currentIndex++;
                    configQuestion();
                }
            } else if (videoQuestionBean.QuestionType == 1) {
                if (audioFile == null) {
                    return;
                }
                mPresenter.postCourseAssignmentVideoAnswer(audioFile);
            }
        }
        if (view == mDataBinding.ivSoundAnimator) {
            JZVideoPlayer.goOnPlayOnPause();
            MediaManager.getInstance().setMediaDataSource(getActivity(), audioFileName);
        }
        if (view == mDataBinding.ivDeleteVoice) {
            mDataBinding.llVoiceShowLayout.setVisibility(View.GONE);
            mDataBinding.llVoiceInputLayout.setVisibility(View.VISIBLE);
            audioFileName = "";
            audioFile = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        JZVideoPlayer.goOnPlayOnPause();
    }

    @Override
    public boolean onRecordPrepare() {
        //检查录音权限
        if (!MPermission.hasPermissions(getActivity(), Manifest.permission.RECORD_AUDIO)) {
            MPermission.with(this)
                    .permissions(Manifest.permission.RECORD_AUDIO)
                    .request();
            return false;
        }
        return true;
    }


    /**
     * 初始化计时器用来更新倒计时
     */
    private void initTimer() {
        recordTotalTime = 0;
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                // 回到主线程
                UIUtils.postTaskSafely(new Runnable() {
                    @Override
                    public void run() {
                        recordTotalTime += 1000;
                        if (recordTotalTime >= maxRecordTime) {
                            mDataBinding.recordAudioButton.invokeStop();
                            timer.cancel();
                        }
                        JZVideoPlayer.goOnPlayOnPause();
                    }
                });
            }
        };
    }

    @Override
    public void onRecordStart() {
        // 暂停
        JZVideoPlayer.goOnPlayOnPause();
        mDataBinding.recordAudioWaveView.start();
        initTimer();
        timer.schedule(timerTask, 0, DEFAULT_MIN_TIME_UPDATE_TIME);
    }

    @Override
    public boolean onRecordStop(String audioPath, long duration) {
        timer.cancel();
        mDataBinding.recordAudioWaveView.stop();
        if (recordTotalTime > minRecordTime) {
            File file = new File(audioPath);
            if (file.exists()) {
                mDataBinding.llVoiceShowLayout.setVisibility(View.VISIBLE);
                mDataBinding.llVoiceInputLayout.setVisibility(View.GONE);
                audioFileName = audioPath;
                audioFile = new File(audioPath);
                durationTime = duration;
                mDataBinding.tvAudioDuration.setText(DateUtil.formatTime(durationTime / 1000));
            }
        } else {
            showToast("时间过短");
            mDataBinding.tvRecordAudioTips.setText("时间过短 取消录音");
            onRecordCancel();
        }
        return false;
    }

    @Override
    public boolean onRecordCancel() {
        mDataBinding.recordAudioWaveView.stop();
        return false;
    }

    @Override
    public void onSlideTop() {
        mDataBinding.tvRecordAudioTips.setText("松开手指 取消录音");
    }

    @Override
    public void onFingerPress() {
        mDataBinding.tvRecordAudioTips.setText("长按话筒 开始录音");
    }

    @Override
    public void onSubmitCourseAssignmentVideoAnswerSuccess(SubmitCourseAssignmentVideoAnswerBean data) {
        if (data != null && !TextUtils.isEmpty(data.VoiceUrl)) {
            videoQuestionBean.answer = data.VoiceUrl;
            videoQuestionBean.duration = durationTime;
            if (currentIndex == totalQuestionCount - 1) {
                mPresenter.postCourseAssignmentVideoRecord(courseAssignmentBean);
            } else {
                currentIndex++;
                configQuestion();
            }
        }
    }

    @Override
    public void onSubmitCourseAssignmentSuccess(SubmitCourseAssignmentBean data) {
        CourseEvent.getInstance().notifyOCourseChanged();
    }

    /**
     * 权限管理
     */
    private final String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
    };

    @Override
    public void update(Observable observer, Object object) {
        super.update(observer, object);
        if (observer instanceof AudioManagerEvent) {
            int focusChange = (int) object;
            if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                //获得焦点之后的操作
                MediaManager.getInstance().start();
            } else {
                //失去焦点之后的操作
                MediaManager.getInstance().pause();
            }
        }
        if (observer instanceof MediaManager) {
            MediaManager.OperatorResultBean operatorResultBean = (MediaManager.OperatorResultBean) object;
            // 获取时长
            if (operatorResultBean.operation == MediaManager.OperatorResultBean.GET_MEDIA_DURATION){
                MediaManager.getInstance().start();
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_PROGRESS_UPDATE){// 更新播放进度

            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_UPDATE){// 更新缓冲进度

            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_START){// 开始播放
                AnimationDrawable animator = (AnimationDrawable) mDataBinding.ivSoundAnimator.getBackground();
                animator.start();
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_STOP){// 开始播放
                AnimationDrawable animator = (AnimationDrawable) mDataBinding.ivSoundAnimator.getBackground();
                animator.stop();
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_COMPLETION){// 播放完成
                AnimationDrawable animator = (AnimationDrawable) mDataBinding.ivSoundAnimator.getBackground();
                animator.stop();
                animator.selectDrawable(0);
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_START){// 开始缓冲

            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_END){// 结束缓冲

            }
        }
    }


    @Override
    public void onDestroyView() {
        JZVideoPlayer.releaseAllVideos();
        MediaManager.getInstance().release();
        AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        audioManager.abandonAudioFocus(null);
        super.onDestroyView();
    }

}
